<template>
  <div class="course-list">
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索课程"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="selectedCategory" @change="handleCategoryChange">
        <el-option
          v-for="category in categories"
          :key="category"
          :label="category"
          :value="category"
        />
      </el-select>
    </div>

    <div class="course-grid">
      <el-card
        v-for="course in courses"
        :key="course.id"
        class="course-card"
        @click="navigateToCourse(course.id)"
      >
        <img :src="course.coverImage" class="course-image" />
        <h3>{{ course.title }}</h3>
        <p>{{ course.description }}</p>
        <div class="course-info">
          <span>讲师: {{ course.instructorName }}</span>
          <span>价格: ¥{{ course.price }}</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { getCourses } from '@/api/courses'

const router = useRouter()
const searchKeyword = ref('')
const selectedCategory = ref('')
const courses = ref([])
const categories = ref([])

const handleSearch = async () => {
  const result = await getCourses({
    keyword: searchKeyword.value,
    category: selectedCategory.value
  })
  courses.value = result.data
}

const handleCategoryChange = () => {
  handleSearch()
}

const navigateToCourse = (courseId: number) => {
  router.push(`/courses/${courseId}`)
}

onMounted(async () => {
  handleSearch()
})
</script>

<style scoped>
.course-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.course-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.course-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>